package com.wcl.hencodertest.test13_multi_touch;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.LogUtils;
import com.wcl.hencodertest.Util;

public class MultiTouchView2 extends View {

    public static final int IMAGE_WIDTH = ConvertUtils.dp2px(300);

    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    private final Bitmap bitmap;
    private float offsetX;
    private float offsetY;
    private float downX;
    private float downY;
    private float originalOffsetX;
    private float originalOffsetY;

    public MultiTouchView2(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        bitmap = Util.getAvatar(IMAGE_WIDTH);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(bitmap, offsetX, offsetY, paint);
    }


    /**
     * 手指的ID不变,但是index会变,所以需要通过记录ID,在使用的时候,通过ID寻找index,event.getX(index);
     *
     * @param event
     * @return
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {

        float sumX = 0;
        float sunY = 0;
        int pointerCount = event.getPointerCount();
        boolean isPointerUp = event.getActionMasked() == MotionEvent.ACTION_POINTER_UP;
        for (int i = 0; i < pointerCount; i++) {
            if (!(isPointerUp && event.getActionIndex() == i)) {
                sumX += event.getX(i);
                sunY += event.getY(i);
            }
        }
        if (isPointerUp) {
            pointerCount -= 1;
        }
        float focusX = sumX / pointerCount;
        float focusY = sunY / pointerCount;

        switch (event.getActionMasked()) {
            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_POINTER_DOWN:
            case MotionEvent.ACTION_POINTER_UP:
                downX = focusX;//记录手指点击按下时候的偏移量,用在后续减掉
                downY = focusY;
                originalOffsetX = offsetX;//记录上次图片移动的位置
                originalOffsetY = offsetY;
                break;
            case MotionEvent.ACTION_MOVE:
                int index = event.getActionIndex();
                LogUtils.i("onTouchEvent: ", index);
                offsetX = focusX - downX + originalOffsetX;
                offsetY = focusY - downY + originalOffsetY;
                invalidate();
                break;
        }

        return true;
    }
}
